package com.book.service;

import com.book.entity.Users;
import com.book.mapper.UserMapper;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @Author zzw2000
 * @Date 2022年08月24日 20:43
 * @Description 描述
 */
@Service
public class UserAuthService implements UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users = userMapper.getPasswordByUsername(username);  //从数据库根据用户名获取密码
        if(Objects.isNull(users))
            throw new UsernameNotFoundException("登录失败，用户名或密码错误！");
        return User   //这里需要返回UserDetails，SpringSecurity会根据给定的信息进行比对
                .withUsername(users.getUsername())
                .password(users.getPassword())   //直接从数据库取的密码
                .roles(users.getRole())   //用户角色
                .build();
    }
}
